#!/usr/bin/python -S
"""
count_.py

Demonstrates the simple protocol, where you just print a record with 'stdout',
instead of a header with 'stdout_boundary', and then the actual stdout.
"""

import os
import json
import sys
import time

import tnet


def log(msg, *args):
  if args:
    msg = msg % args
  print >>sys.stderr, 'count_: ' + msg


# this "persists" betwen invocations
count = 0

# The old one goes here.
def main_iter(request):
  global count
  count += 1
  log('incremented count to %d', count)

  argv = request['argv']

  stdout = 'count = %d\n' % count
  stdout += json.dumps(request, indent=2)

  # Write response.  With the global.
  response = {
      'stdout': stdout,
      # TODO: stderr should really go on actaul stderr.
      'stderr': 'exit %d\n' % count,
      'status': count
      }
  return response


# TODO: Factor this out into a library
def loop(argv):
  boundary = os.getenv('PGI_BOUNDARY')
  assert boundary, 'PGI_BOUNDARY required'

  # Simulate slow startup.
  pid = os.getpid()
  log('Hello from count_.py, pid %d.  Sleeping 1 second', pid)
  time.sleep(1)

  while True:
    log('waiting for PGI input')
    try:
      request = tnet.load(sys.stdin)
    except EOFError:
      break

    cwd = request['cwd']
    os.chdir(cwd)

    response = main_iter(request)

    sys.stdout.write(tnet.dumps(response))

    sys.stdout.flush()
    log('flushed')

    # ISSUE: We could write more than we're entitled to.  I think 'waiting for
    # PGI input' is going to be lost.
    print >>sys.stderr, boundary

  return 0


def main(argv):
  if os.getenv('PGI'):
    return loop(argv)
  else:
    # Run in non-persistent mode
    return main_iter(argv[1:])


if __name__ == '__main__':
  sys.exit(main(sys.argv))
